<template>
  <el-tabs
    v-model="activeTab"
    type="card"
    @tab-click="handleTabClick"
    class="content-tabs"
    closable
    @tab-remove="removeTab"
  >
    <el-tab-pane
      v-for="tab in dynamicTabs"
      :key="tab.name"
      :label="tab.label"
      :name="tab.name"
      :closable="tab.name !== '/admin/dashboard'"
    />
  </el-tabs>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const tabMap = {
  '/admin/dashboard': '仪表盘',
  '/admin/users': '用户管理',
  '/admin/documents': '文档管理',
  '/admin/system': '系统管理',
  '/admin/roles': '角色管理',
  '/admin/permissions': '权限管理',
  '/admin/knowledge-bases': '知识库管理',
  '/admin/qa': '问答管理',
  '/admin/vectors': '向量管理',
  '/admin/profile': '个人信息'
}

const activeTab = ref(route.path)
const dynamicTabs = ref([])

// 初始化时默认添加仪表盘标签页
const initTabs = () => {
  // 确保仪表盘标签页始终存在
  if (!dynamicTabs.value.find(tab => tab.name === '/admin/dashboard')) {
    dynamicTabs.value.unshift({
      name: '/admin/dashboard',
      label: '仪表盘'
    })
  }
}

function addTab(path) {
  console.log('Adding tab for path:', path)
  
  // 检查路径是否有效
  if (!path || path === 'undefined' || path === 'null') {
    console.error('Invalid path:', path)
    return
  }
  
  // 仪表盘标签页已经在初始化时添加，这里不需要重复处理
  if (path === '/admin/dashboard') {
    return
  }
  
  if (!dynamicTabs.value.find(tab => tab.name === path)) {
    const newTab = {
      name: path,
      label: tabMap[path] || '未命名'
    }
    console.log('Adding new tab:', newTab)
    dynamicTabs.value.push(newTab)
  }
}

watch(
  () => route.path,
  (newPath) => {
    console.log('Route changed to:', newPath)
    
    // 检查新路径是否有效
    if (!newPath || newPath === 'undefined' || newPath === 'null') {
      console.error('Invalid route path:', newPath)
      return
    }
    
    activeTab.value = newPath
    addTab(newPath)
  },  
  { immediate: true }
)

// 初始化标签页
initTabs()

function handleTabClick(tab) {
  console.log('Tab clicked:', tab)
  console.log('Tab name:', tab.name)
  console.log('Tab label:', tab.label)
  console.log('Tab props:', tab.props)
  console.log('Tab paneName:', tab.paneName)
  console.log('Current route:', route.path)
  
  // Element Plus 的 tab-click 事件可能传递的是不同的数据结构
  // 尝试多种方式获取标签页名称
  let tabName = tab.name || tab.paneName || tab.props?.name
  
  // 如果还是获取不到，尝试从当前激活的标签页获取
  if (!tabName) {
    tabName = activeTab.value
    console.log('Using activeTab as fallback:', tabName)
  }
  
  // 检查tabName是否存在且有效
  if (!tabName || tabName === 'undefined' || tabName === 'null') {
    console.error('Invalid tab name:', tabName)
    console.error('Tab object:', tab)
    return
  }
  
  if (tabName !== route.path) {
    console.log('Navigating to:', tabName)
    
    // 直接使用路由跳转，不使用nextTick
    try {
      if (router && typeof router.push === 'function') {
        router.push(tabName).then(() => {
          console.log('Navigation successful')
        }).catch(err => {
          console.error('Router navigation failed, using fallback:', err)
          // 如果路由跳转失败，使用 window.location 作为备选
          window.location.href = tabName
        })
      } else {
        console.warn('Router not available, using fallback navigation')
        window.location.href = tabName
      }
    } catch (error) {
      console.error('Navigation error:', error)
      // 最后的备选方案
      window.location.href = tabName
    }
    
    // 添加点击动画效果
    const tabElement = document.querySelector(`[data-name="${tabName}"]`)
    if (tabElement) {
      // 添加点击波纹效果
      const ripple = document.createElement('div')
      ripple.style.cssText = `
        position: absolute;
        top: 50%;
        left: 50%;
        width: 0;
        height: 0;
        background: rgba(64, 158, 255, 0.3);
        border-radius: 50%;
        transform: translate(-50%, -50%);
        transition: all 0.3s ease;
        pointer-events: none;
        z-index: 1;
      `
      tabElement.style.position = 'relative'
      tabElement.appendChild(ripple)
      
      setTimeout(() => {
        ripple.style.width = '100px'
        ripple.style.height = '100px'
        ripple.style.opacity = '0'
      }, 10)
      
      setTimeout(() => {
        if (ripple.parentNode) {
          ripple.parentNode.removeChild(ripple)
        }
      }, 300)
    }
  }
}

function removeTab(targetName) {
  console.log('Removing tab:', targetName)
  
  // 防止仪表盘标签页被关闭
  if (targetName === '/admin/dashboard') {
    console.log('阻止关闭仪表盘标签页')
    return
  }
  const idx = dynamicTabs.value.findIndex(tab => tab.name === targetName)
  if (idx !== -1) {
    dynamicTabs.value.splice(idx, 1)
    // 关闭当前激活标签时，自动切换到左侧或仪表盘页面
    if (activeTab.value === targetName) {
      const nextTab = dynamicTabs.value[idx - 1] || dynamicTabs.value[0] || { name: '/admin/dashboard' }
      try {
        if (router && typeof router.push === 'function') {
          router.push(nextTab.name)
        } else {
          window.location.href = nextTab.name
        }
      } catch (error) {
        console.error('Navigation error in removeTab:', error)
        window.location.href = nextTab.name
      }
    }
  }
}

// 调试信息
console.log('ContentTabs component initialized')
console.log('Initial route:', route.path)
console.log('Initial activeTab:', activeTab.value)
console.log('Initial dynamicTabs:', dynamicTabs.value)
console.log('TabMap:', tabMap)
</script>

<style scoped>
.content-tabs {
  margin-bottom: 16px;
  position: sticky;
  top: 0;
  z-index: 2;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

/* 标签页样式优化 */
:deep(.el-tabs__header) {
  margin: 0;
  padding: 0 16px;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0;
}

:deep(.el-tabs__item) {
  height: 40px;
  line-height: 40px;
  padding: 0 16px;
  font-size: 14px;
  color: #666;
  border: 1px solid transparent;
  border-radius: 6px 6px 0 0;
  margin-right: 4px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  cursor: pointer;
}

:deep(.el-tabs__item::before) {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1;
}

:deep(.el-tabs__item:hover) {
  color: #409eff;
  border-color: #e1f3ff;
  background: #f8fbff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
  background: #fff;
  border-color: #409eff;
  border-bottom-color: #fff;
  font-weight: 500;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

:deep(.el-tabs__item.is-active::before) {
  opacity: 0.05;
}

/* 关闭按钮样式 */
:deep(.el-tabs__item .el-icon-close) {
  margin-left: 8px;
  font-size: 12px;
  color: #999;
  transition: all 0.2s ease;
}

:deep(.el-tabs__item .el-icon-close:hover) {
  color: #f56c6c;
  transform: scale(1.2);
}

/* 隐藏仪表盘标签的关闭按钮 */
:deep(.el-tabs__item:first-child .el-icon-close) {
  display: none !important;
}

/* 仪表盘标签页特殊样式 - 确保不可关闭 */
:deep(.dashboard-tab) {
  pointer-events: none;
}

:deep(.dashboard-tab .el-tabs__item) {
  pointer-events: auto;
}

:deep(.dashboard-tab .el-tabs__item .el-icon-close) {
  display: none !important;
  pointer-events: none !important;
}

/* 仪表盘标签页特殊标识 */
:deep(.dashboard-tab .el-tabs__item) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
  border-color: #667eea;
}

:deep(.dashboard-tab .el-tabs__item:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  color: white;
  border-color: #5a6fd8;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

:deep(.dashboard-tab .el-tabs__item.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: #667eea;
  border-bottom-color: #fff;
  font-weight: 700;
  transform: translateY(-1px);
  box-shadow: 0 2px 12px rgba(102, 126, 234, 0.4);
}

/* 标签页内容区域 */
:deep(.el-tabs__content) {
  display: none;
}

/* 标签页切换动画 */
:deep(.el-tabs__item) {
  user-select: none;
}

:deep(.el-tabs__item:active) {
  transform: scale(0.98) translateY(-1px);
}

/* 新增标签动画 */
@keyframes tabSlideIn {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

:deep(.el-tabs__item) {
  animation: tabSlideIn 0.3s ease;
}
</style>
